#noCompile

fs = require 'fs'
markdown = require('markdown').markdown
low = require('lowdb')
express = require("express")
path = require("path")
logger = require("morgan")
compress = require('compression')
cookieParser = require("cookie-parser")
bodyParser = require("body-parser")
routes = require("./routes/index")
users = require("./routes/users")
app = express()

app.set 'port', (process.env.PORT || 5000)

app.set "views", path.join(__dirname, "views")
app.set 'view engine', 'coffee'
app.set "view options", layout: false
app.engine 'coffee', require('coffeecup').__express
app.engine 'md', (path, options, callback) ->
	fs.readFile path, 'utf8', (err, str) ->
		return callback(err) if err
		console.log options
		callback null, markdown.toHTML(str)

app.use logger("dev")
app.use compress()
#app.use require('express-partials')
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: false)
app.use cookieParser()
app.use express.static path.join(__dirname, "assets"), { maxAge: 7*24*60*60*1000 }
app.use "/", routes
app.use "/users", users

db = low('db.json')

app.get "/blog", (req, res) ->
	data = db('files').where({ ok: "1" }).value()
	res.render "blog", 
		data: data,
		md: markdown
	return

app.get "/blog/:id", (req, res) ->
	fs.readFile "blog/#{req.params.id}.md", 'utf8', (err, str) ->
		console.log err if err
		data = db('files').find({ id: "#{req.params.id}" }).value()
		res.render "post",
			body: markdown.toHTML(str)
			data: data
	return

app.get "/about", (req, res) ->
	res.render "about"
	return

app.get "/article", (req, res) ->
	res.render "article", layout: "layout"
	return

# catch 404
app.use (req, res, next) ->
	res.status 404
	res.render "404"
	return

app.use (err, req, res, next) ->
	res.status err.status or 500
	res.render "error",
		message: err.message
		error: err
	return

app.listen app.get('port'), () ->
	console.log "Node running at localhost:#{app.get('port')}, ENV is #{process.env.ENV?='productive'}"

module.exports = app
